package com.lgl.mes.workReport.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lgl.mes.basedata.entity.SpTableManager;
import com.lgl.mes.common.Result;
import com.lgl.mes.common.util.DateUtil;
import com.lgl.mes.common.util.log.SysLog;
import com.lgl.mes.daily.entity.SpDailyPlan;
import com.lgl.mes.daily.request.spDailyPlanReq;
import com.lgl.mes.daily.service.ISpDailyPlanService;
import com.lgl.mes.group.entity.SpGroup;
import com.lgl.mes.order.service.ISpOrderService;
import com.lgl.mes.workReport.entity.SpWorkReport;
import com.lgl.mes.workReport.request.spWorkreportReq;
import com.lgl.mes.workReport.service.ISpWorkReportService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import com.lgl.mes.common.BaseController;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 75039960@qq.com
 * @since 2024-08-10
 */
@Controller
@RequestMapping("/workReport")
public class SpWorkReportController extends BaseController {

    @Autowired
    private ISpDailyPlanService iSpDailyPlanService;

    @Autowired
    private ISpOrderService iSpOrderService;

    @Autowired
    private ISpWorkReportService iSpWorkReportService;

    @ApiOperation("报工列表界面UI")
    @ApiImplicitParams({@ApiImplicitParam(name = "model", value = "模型", defaultValue = "模型")})
    @GetMapping("/list-ui")
    public String listUI(Model model) {

        return "workreport/list";
    }


    /**
     * 报工管理修改界面
     *
     * @param record 平台表对象
     * @return 更改界面
     */
    @ApiOperation("报工管理修改界面")
    @GetMapping("/add-or-update-ui")
    public String addOrUpdateUI(Model model, SpTableManager record) {
        if (StringUtils.isNotEmpty(record.getId())) {
            SpWorkReport spWorkReport = iSpWorkReportService.getById(record.getId());
            model.addAttribute("result", spWorkReport);
        }
        return "workreport/addOrUpdate";
    }

    /**
     * 报工管理界面分页查询
     *
     * @param req 请求参数
     * @return Result 执行结果
     */
    @ApiOperation("报工管理界面分页查询")
    @ApiImplicitParams({@ApiImplicitParam(name = "req", value = "请求参数", defaultValue = "请求参数")})
    @PostMapping("/page")
    @ResponseBody
    public Result page(spWorkreportReq req) {   //  //spDailyPlanReq
        QueryWrapper<SpWorkReport> queryWrapper =new QueryWrapper();
        if (StringUtils.isNotEmpty(req.getOrderCode()))
        {
            queryWrapper.like("order_code",req.getOrderCode());
        }

        if (StringUtils.isNotEmpty(req.getPlanCode()))
        {
            queryWrapper.like("plan_code",req.getPlanCode());
        }



        if (req.getCreateTime1() !=null && !req.getCreateTime1().isEmpty())
        {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate= LocalDate.parse(req.getCreateTime1(), formatter);
            //queryWrapper.ge("createTime",ld);
            queryWrapper.apply("UNIX_TIMESTAMP(create_time) >= UNIX_TIMESTAMP('" + localDate + "')");
        }


        if (req.getCreateTime2() !=null && !req.getCreateTime2().isEmpty())
        {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
            LocalDate localDate= LocalDate.parse(req.getCreateTime2(), formatter);
            queryWrapper.apply("UNIX_TIMESTAMP(create_time) <= UNIX_TIMESTAMP('" + localDate + "')");
        }

        IPage result = iSpWorkReportService.page(req,queryWrapper);



        return Result.success(result);
    }



    @SysLog("修改，新增报工")
    @ApiOperation("报工管理修改、新增")
    @PostMapping("/add-or-update")
    @ResponseBody
    public Result addOrUpdate(SpWorkReport   record)  throws Exception {
        /*
        if(record.getPlanDate()!=null ) {
            //record.setPlanDate(DateUtil.GetShortStampString(record.getPlanDate().toString()));
            record.setPlanDate(DateUtil.GetStampString(record.getPlanDate().toString()));
        }*/

         boolean  ret=  iSpWorkReportService.saveOrUpdate(record);
         if(ret) //更新计划的产量和不良，更新订单的产量和不良，时长
         {
             iSpWorkReportService.UpdateOrderAndPlan (record.getPlanCode());
         }

        return Result.success();
    }


    /**
     * 删除报工
     *
     * @param req 请求参数
     * @return Result 执行结果
     */
    @SysLog("删除日计划")
    @ApiOperation("删除报工")
    @ApiImplicitParams({@ApiImplicitParam(name = "req", value = "报工实体", defaultValue = "报工实体")})
    @PostMapping("/delete")
    @ResponseBody
    public Result deleteByTableNameId(SpWorkReport req) throws Exception {

        if(req.getId()==null)
        {
            return  Result.failure("没有报工ID");
        }

       boolean ret =  iSpWorkReportService.removeById(req.getId());
        if(ret) //更新计划的产量和不良，更新订单的产量和不良，时长
        {
            iSpWorkReportService.UpdateOrderAndPlan (req.getPlanCode());
        }

        return Result.success();
    }


    @ApiOperation("批量删除报工")
    @ApiImplicitParams({@ApiImplicitParam(name = "ids", value = "workreport ids", defaultValue = "workreport ids")})
    @PostMapping("/batchDelete")
    @ResponseBody
    public Result batchDelete( String  ids) throws Exception {

        String[] tempList = ids.split(",");
        boolean  ret = false;
        for (String id  :  tempList)
        {
            String  planCode = iSpWorkReportService.getById(id).getPlanCode();
            ret =iSpWorkReportService.removeById(id);
            if(ret) //更新计划的产量和不良，更新订单的产量和不良，时长
            {
                if(planCode != null  &&  !planCode.isEmpty())
                    ret =iSpWorkReportService.UpdateOrderAndPlan (planCode);
                    //if(!ret)   return Result.failure("更新数据失败！");
            }
        }


        return Result.success();
    }

    @ResponseBody
    @RequestMapping(value = "/list", method = RequestMethod.GET, produces = "application/json")
    public Result getList() throws Exception {


        List<SpWorkReport> list = iSpWorkReportService.list();

        return Result.success(list);
    }


}
